import React, { Component } from 'react';
import App from 'layout/App.js'
import { FormControl, Button, Table, Pagination, Modal, Radio, Select, Popconfirm, Breadcrumb, Row, Col} from 'tinper-bee';
import { addWorkFileList, getManagerList, getUserBaseDataUrl, searchItemWorkFileList, editWorkFileList, searchPkFromNc, searchOrgs,searchWorkProList , getUseNewTeamReq } from './workarchives.config.js';
import CommonModal from './../../components/ProjectFilesModal/index.jsx';
import ManagerModalContent from './ManagerModalContent.jsx';
import EnterpriseModalContent from './EnterpriseModalContent.jsx';
import MapModal from './../../components/ProjectMap/mapModal.jsx';
import MemberModalContent from './MemberModalContent.jsx';
import { vendorsDanger as danger, vendorsSuccess as success, vendorsFmtDate as fmtDate, vendorsWarning as warning } from 'utils/config.js';
import './index.less';
import zhCN from 'rc-calendar/lib/locale/zh_CN';
import enUS from 'rc-calendar/lib/locale/en_US';
import DatePicker from 'bee-datepicker';
import TreeSelect from 'bee-tree-select';
import 'bee-tree-select/build/TreeSelect.css';
import Switch from 'bee-switch';
import moment from 'moment';
moment.locale('zh-cn');
import PersonnelEnterpriseModalContent from "./PersonnelEnterPriseModalContent.jsx";

import jdiwork from '../../utils/jdiwork'
let tenantId;
let cookieStr = document.cookie.split(';').find(cur => cur.indexOf('tenantid=') != -1)
if (cookieStr) {
    tenantId = cookieStr.split('=')[1];
}

export default class WorkEditFileItem extends Component {
    constructor (props){
        super(props);
        this.state = {
            code: '',
            name: '',
            startDate: '',
            endDate: '',
            description: '',
            manager: '',
            checked: false,
            showModal: false,
            contentType: 'normal',
            saveItem: {},
            modalSize: 'sm',
            modalTitle: '',
            managerData: [],
            managerRec: {},
            handlerModalCancel: null,
            handlerModalConfirm: null,
            enterpriseListData: [],
            enterpriseRole: '10',
            enterpriseRoleArray: [],
            enterpriseItem: null,
            userName: '',
            snameDanger: false,
            scodeDanger: false,
            approvalDateDanger: false,
            enterpriseDivIndex: 0,
            membersData: null,
            insertEnterpriseVOs: [],
            updateEnterpriseVOs: [],
            updateMemberVOs:[],
            delPkTeamEnt: [],
            insertMemberVOs: [],
            delPkTeamMember: [],
            pkProject: '',
            changeFlag: '',
            pkTenant: '',
            memberArray: [],
            managerName: '',
            chooseDeleteIndex: null,
            creationtime: null,
            ncStatus: false,
            projectState:'',
            projectStatusName:'',
            projectStateValue:'',
            orgList: [],
            orgValue:null,
            orgName: '',
            procedureList: [],
            procedureValue: [],
            mapModalShow: false,
            curLocation: {},
            isUseNewTeam : false,
			enterpriseItems:[],
			enterpriseRoleS : []
        }
    }

    componentDidMount() {
        this.getUseNewTeam(); 
        
    }

    getUseNewTeam = () =>{
		let _me = this;
		getUseNewTeamReq({}).then((res)=>{
			if (res.data.resultCode !== "busi_ex") {
				_me.setState({
					isUseNewTeam: res.data.result
				}, ()=>{
					this.getUserBaseData();
                    let pkSrc = sessionStorage.getItem('filePkSrc');
                    this.getProcedures();
                    if (pkSrc !== 'null') {
                        this.initFromNc(pkSrc);
                        this.setState({
                            ncStatus: true
                        })
                    } else {
                        this.init();
                    }
				});
			}
		}).catch((error)=>{
		})
			
	}
    init = () => {
        let pkProject = sessionStorage.getItem('filePkproject');
        searchItemWorkFileList({'id': pkProject, 'isAjax': 1, 'ieStamp': new Date().getTime()},
            res => {
                let data = res.data.result;
                if (data.teamEnterpriseViewVOs) {
                    data.teamEnterpriseViewVOs.forEach((item, index) => {
                        item['defaultEntName'] = item['enterpriseName'];
                        this.state.enterpriseRoleArray.push(String(item.entRole));
                        if (item.teamMemberViewVOs) {
                            item.teamMemberViewVOs.forEach((item) => {
                                item['userEmail'] = item['email'];
                                item['userMobile'] = item['phoneNo'];
                                item['key'] = item['userId'] || item['pkUser'];
                            })
                        } else {
                            item.teamMemberViewVOs = []
                        }
                    })
                } else {
                    data.teamEnterpriseViewVOs = []
                }
                
                this.setState({
                    startDate: data.approvalDate,
                    name: data.sname,
                    code: data.scode,
                    endDate: data.endDate,
                    description: data.description,
                    checked: data.iskey,
                    manager: data.manager,
                    managerName: data.managerName,
                    enterpriseListData: data.teamEnterpriseViewVOs,
                    pkProject: pkProject,
                    changeFlag: data.changeFlag,
                    pkTenant: data.pkTenant,
                    creationtime: data.creationtime,
                    projectStateValue:data.projectState,
                    projectStatusName:data.projectStatusName,
                    projectState:this.getProjectState(data.projectState),
                    orgValue: data.orgName,
                    orgName: data.orgName,
                    procedureValue: data.procedure&&data.procedure.map(cur=>cur.pkProcedure),
                    curLocation: {
                        lng: data.longitude,
                        lat: data.latitude,
                        address: data.address,
                    },
                });
                sessionStorage.setItem('oldEnterpriseKey', data.managerEnt)
            },
            error=>{}
        )
    }
    initFromNc = (pkSrc)=>{
        searchPkFromNc({'pkSrc': pkSrc, 'isAjax': 1},
            res=>{
                let data = res.data.result;
                if(data.teamEnterpriseViewVOs){
                    data.teamEnterpriseViewVOs.forEach((item, index)=>{
                        item['defaultEntName'] = item['enterpriseName'];
                        this.state.enterpriseRoleArray.push(String(item.entRole));
                        if(item.teamMemberViewVOs){
                            item.teamMemberViewVOs.forEach((item)=>{
                                item['userEmail'] = item['email'];
                                item['userMobile'] = item['phoneNo'];
                                item['key'] = item['userId'] || item['pkUser'];
                            })
                        }else{
                            item.teamMemberViewVOs = []
                        }
                    })
                }else {
                    data.teamEnterpriseViewVOs = []
                }
                this.setState({
                    startDate: data.approvalDate,
                    name: data.sname,
                    code: data.scode,
                    endDate: data.endDate,
                    description: data.description,
                    checked: data.iskey,
                    manager: data.manager,
                    managerName: data.managerName,
                    enterpriseListData: data.teamEnterpriseViewVOs,
                    pkProject: data.pkProject,
                    changeFlag: data.changeFlag,
                    pkTenant: data.pkTenant,
                    creationtime: data.creationtime,
                    projectStateValue:data.projectState,
                    projectStatusName:data.projectStatusName,
                    projectState:this.getProjectState(data.projectState),
                    orgValue: data.orgName,
                    orgName: data.orgName,
                    procedureValue: data.procedure&&data.procedure.map(cur=>cur.pkProcedure),
                    curLocation: {
                        lng: data.longitude,
                        lat: data.latitude,
                        address: data.address,
                    },
                });
                sessionStorage.setItem('oldEnterpriseKey', data.managerEnt)
            },
            error => {
            }
        )
    }
    getProcedures = ()=>{
		let _me = this;
		searchWorkProList({ 'isAjax': 1, 'ieStamp': new Date().getTime(), status: 1 })
		.then(function(res){
			if (res.data.resultCode != 'busi_ex') {
				if(res.data.result.length !== 0){
					let data = res.data.result;
					data&&data.forEach(cur=>{
						cur.key = cur.pkProcedure;
						cur.title = cur.scode+ ' ' +cur.sname;
						cur.value = cur.pkProcedure;
					})
					// 加工后台数据添加 name, key, id 组件组件需要属性
					// _me.loopNextData(data);
					_me.setState({
						procedureList: data
					});
				}
			} else {
				danger({'text': res.data.exMsg})
			}
		})
	}
    getUserBaseData = () => {
        let _me = this;
        getUserBaseDataUrl({'isAjax': 1, 'ieStamp': new Date().getTime()},
            res => {
                if (res.data.result !== null) {
                    _me.setState({
                        userName: res.data.result.userName
                    });
                } else {
                    _me.setState({
                        userName: ''
                    });
                }
            },
            error => {
            }
        )
    }
    getColumns = (type) => {
        let _me = this;
        return [
            {title: "姓名", dataIndex: "userName", className: 'text-overflow', key: "userName", width: '20%'},
            {title: "电话", dataIndex: "userMobile", className: 'text-overflow', key: "userMobile", width: '40%'},
            {title: "邮箱", dataIndex: "userEmail", key: "userEmail", width: '20%'},
            {
                title: "", dataIndex: "y", key: "y", width: '20%',
                render(text, rec, index) {
                    return <div className="table-operation">
                        <a href="javascript:;" onClick={_me.handlerDeleteMember(index)}>删除</a>
                    </div>
                }
            }
        ]
    }
    handlerDeleteMember = (index) => () => {
        setTimeout(() => {
            let delPkTeamMember = this.state.delPkTeamMember;
            let insertMemberVOs = this.state.insertMemberVOs;
            let deleteMemberItem = this.state.enterpriseListData[this.state.enterpriseDivIndex].teamMemberViewVOs[index];
            if (deleteMemberItem.userRole === 0 || deleteMemberItem.pkUser === this.state.manager) {
                danger({text: '项目经理不可删除！'})
                return;
            }
            insertMemberVOs.forEach((item, index) => {
                if (item['userName'] == deleteMemberItem.userName && item['userRole'] == deleteMemberItem.userRole) {
                    insertMemberVOs.splice(index, 1);
                }
            })
            delPkTeamMember.push(deleteMemberItem);
            this.state.enterpriseListData[this.state.enterpriseDivIndex].teamMemberViewVOs.splice(index, 1);
            this.setState({
                enterpriseListData: this.state.enterpriseListData,
                delPkTeamMember,
                insertMemberVOs
            });
        }, 0)
    }
    getCompnents = (type = 'normal') => {
        switch (type) {
            case 'normal':
                return '取消后本次所填信息将会丢失！请确认';
                break;
            case 'enterprise':
                return <EnterpriseModalContent saveEnterpriseItem={this.handlerSaveEnterpriseItem}
                                               saveEnterpriseRole={this.handlerSaveEnterpriseRole}/>;
                break;
            case 'organize':
                return <MemberModalContent isUseNewTeam = {this.state.isUseNewTeam} data={this.state.membersData} saveMemberItem={this.handlerSaveMemberItem}
                                           hasChooseMemberData={this.state.enterpriseListData[this.state.enterpriseDivIndex].teamMemberViewVOs}/>;
                break;
            case 'managerModal':
                return <ManagerModalContent isUseNewTeam = {this.state.isUseNewTeam}  data={this.state.managerData}
                                            saveManagerRecord={this.handlerSaveMangerRecord}/>;
                break;
            case 'enterpriseDelete':
                return '确定是否删除这条信息？'
                break;
           	case 'personnelenterprise':
				return <PersonnelEnterpriseModalContent pkOrgs ={this.state.orgValue} saveEnterpriseItem={this.handlerSaveEnterpriseItem} saveEnterpriseRole={this.handlerSaveEnterpriseRole} defaultChooseEnterprise = {this.state.enterpriseListData}/>;
				break;
        }
    }
    handlerSaveMemberItem = (item) => {
        item.map((memberItem)=>{

            if(this.state.isUseNewTeam){
				memberItem["userEmail"] = memberItem.email;
				memberItem["userMobile"] = memberItem.phone;
				memberItem["userName"] = memberItem.sname
			}else{
				memberItem["userEmail"] = memberItem.userEmail;
				memberItem["userMobile"] = memberItem.userMobile;
				memberItem["userName"] = memberItem.userName
			}
		
		})
        this.setState({
            memberArray: item
        });
    }
    handlerMemberConfirm = () => {
        let newObj = {};
        let insertMemberVOs = this.state.insertMemberVOs;
        let playData = this.state.enterpriseListData[this.state.enterpriseDivIndex].teamMemberViewVOs;
        insertMemberVOs.push(...this.state.memberArray)
        playData.push(...this.state.memberArray);
        playData.forEach((item) => {
            if (item['userRole'] !== "0"|| item['userRole'] !== 0 || item['pkUser'] !== this.state.manager) {
                item['userRole'] = this.state.enterpriseRole;
            }
            item['pkUser'] = item.pkUser|| item.userId|| item.pkPersonnel
        })
        for (let i = 0; i < playData.length; i++) {
            if (newObj[playData[i]['userName']]) {
                newObj[playData[i]['userName']]++
                playData.splice(i, 1);
                i--;
            } else {
                newObj[playData[i]['userName']] = 1;
            }
        }
        this.setState({
            enterpriseListData: this.state.enterpriseListData,
            showModal: false,
            insertMemberVOs
        });
    }
    handlerSaveEnterpriseItem = (item) => {
        if(this.state.isUseNewTeam){

			this.setState({
				enterpriseItems: item
			});
		}else{
			this.setState({
				enterpriseItem: item 
			});
		}
       
    }
    handlerSaveEnterpriseRole = (item) => {
        if(this.state.isUseNewTeam){
			this.setState({
				enterpriseRoleS: item
			});
		}else{
			this.setState({
				enterpriseRole: item
			});
		}
    }
    onChange = (d) => {
    }
    onStartSelect = (date) => {
        if (date !== null) {
            this.setState({
                startDate: new Date(date._d).getTime()
            });
        }
    }
    onEndSelect = (date) => {
        if (date !== null) {
            this.setState({
                endDate: new Date(date._d).getTime()
            });
        }
    }
    handlerSaveCode = (e) => {
        let value = e.target.value;
        let regCode = /[^a-zA-Z0-9\_-]+/img;
        value = value.replace(regCode, '');
        if (value.length >= 20) {
            value = value.substring(0, 20);
        }
        this.setState({
            code: value
        });
    }
    handlerSaveName = (e) => {
        let value = e.target.value;
        if (value.length >= 50) {
            value = value.substring(0, 50);
        }
        this.setState({
            name: value
        });
    }
    handlerSaveDescription = (e) => {
        let value = e.target.value;
        if (value.length >= 300) {
            value = value.substring(0, 300);
        }
        this.setState({
            description: value
        });
    }
    handlerSwitchChoose = () => {
        this.setState({
            checked: !this.state.checked
        });
    }
    onhide = () => {
        this.setState({
            showModal: false
        });
    }
    handlerDeleteClose = () => {
        this.setState({
            showModal: false
        });
    }
    handlerDeleteConfirm = () => {
        this.setState({
            showModal: false
        });
    }
    handlerCreateEnterprise = () => {
        
        this.setState({
            showModal: true,
            contentType:this.state.isUseNewTeam? "personnelenterprise": 'enterprise',
            modalTitle: '添加企业',
            modalSize: 'lg',
            handlerModalCancel: this.onhide,
            handlerModalConfirm:  this.state.isUseNewTeam ? this.handlerSaveEnterpriseS : this.handlerSaveEnterprise ,
            enterpriseItem: null,
            enterpriseRole:  '10',
            enterpriseRoleS:[],
			enterpriseItems: []
        })

    }
    handlerSaveEnterprise = () => {
        if (this.state.enterpriseItem === null) return;
        let enterpriseArray = this.state.enterpriseListData;
        let insertEnterpriseVOs = this.state.insertEnterpriseVOs;
        let isHasSameEnterprise = false;
        this.state.enterpriseRoleArray.push(String(this.state.enterpriseRole));
        enterpriseArray.forEach((item, index) => {
            if (item.defaultEntName === this.state.enterpriseItem.name) {
                danger({'text': '已经选择了该企业！'});
                isHasSameEnterprise = true;
            }
        })
        if (isHasSameEnterprise) return;
        enterpriseArray.push({
            pkEnterprise: this.state.enterpriseItem.id,
            entRole: this.state.enterpriseRole,
            defaultEntName: this.state.enterpriseItem.name,
            teamMemberViewVOs: []
        });
        insertEnterpriseVOs.push({
            pkEnterprise: this.state.enterpriseItem.id,
            entRole: this.state.enterpriseRole,
            defaultEntName: this.state.enterpriseItem.name,
            teamMemberViewVOs: []
        });
        this.setState({
            showModal: false,
            enterpriseListData: enterpriseArray,
            enterpriseRoleArray: this.state.enterpriseRoleArray,
            insertEnterpriseVOs
        });
    }

    	//使用新版本的团队功能，保存企业
	handlerSaveEnterpriseS = () =>{
		if(!this.state.enterpriseItems.length) return;
        let enterpriseArray = this.state.enterpriseListData;
        let insertEnterpriseVOs = this.state.insertEnterpriseVOs;
		let isHasSameEnterprise = false;
        this.state.enterpriseRoleArray.concat(this.state.enterpriseRoleS);
        
		enterpriseArray.forEach((item, index)=>{
			this.state.enterpriseItems.find((enterpriseItem)=>{
				if(item.defaultEntName === enterpriseItem.name || item.pkEnterprise === enterpriseItem.pkEnterprise){
					danger({'text': `已经选择[${enterpriseItem.name}]企业！`});
					isHasSameEnterprise = true;
				}
			})
			
		})
		if(isHasSameEnterprise) return;


        
		this.state.enterpriseItems.map((item,index)=>{
			enterpriseArray.push({
				pkEnterprise: item.pkEnterprise,
				entRole:item.role ? item.role.toString() :item.entRole.toString(),
				defaultEntName: item.name,
				teamMemberViewVOs: []
            });
            insertEnterpriseVOs.push({
                pkEnterprise: item.pkEnterprise,
				entRole:item.role ? item.role.toString() :item.entRole.toString(),
				defaultEntName: item.name,
				teamMemberViewVOs: []
            });
            this.state.enterpriseRoleArray.push(item.role ? item.role.toString() :item.entRole.toString())
		})
		
		this.setState({
			showModal: false,
			enterpriseListData: enterpriseArray,
            enterpriseRoleArray: this.state.enterpriseRoleArray,
            insertEnterpriseVOs
		});
    }
    
    	//根据组织自动带出业主方企业的后续
    chooseOrgAutoAddEnterprise = (data) => {
		let roleData = [];
	
		let enterpriseArray = this.mapEnterprise(data);
		roleData = this.mapRole(enterpriseArray);
		
		this.setState({
			enterpriseListData :this.state.enterpriseListData.concat(enterpriseArray),//选组织默认把对应组织下的业主方的企业带出
			enterpriseItems: this.state.enterpriseItems.concat(enterpriseArray),
			enterpriseRoleS : this.state.enterpriseRoleS.concat(roleData),
			enterpriseRoleArray : this.state.enterpriseRoleS.concat(roleData),
		})
	}

	mapEnterprise = (data) =>{
		let enterpriseArray = [];
		let selectedPks = [];
		this.state.enterpriseItems.map((item, index)=>{
			selectedPks.push(item.pkEnterprise)
		})
		data.map((item, index)=>{
			if(selectedPks.includes(item.pkEnterprise)){
				return;
			}
			enterpriseArray.push({
				pkEnterprise: item.pkEnterprise,
				entRole:item.role,
				defaultEntName: item.name,
				teamMemberViewVOs: []
			});
		})
		return enterpriseArray
	}
	mapRole = (data) =>{
		let roleData = []
		data.map((item, index)=>{
			roleData.push(item.role ? item.role.toString() : item.entRole.toString())
		})
		return roleData
	}

    handlerSaveItem = () => {
        let project = Object.assign({},	{sname: this.state.name},
            {pkOrg: this.state.orgValue},
            {approvalDate: this.state.startDate},
            {endDate: this.state.endDate},
            {projectState: this.state.projectStateValue},
            {scode: this.state.code},
            {iskey: this.state.checked},
            {description: this.state.description},
            {manager: this.state.manager},
            {pkProject: this.state.pkProject},
            {changeFlag: this.state.changeFlag},
            {procedures: this.state.procedureValue},
            {address: this.state.curLocation.address},
            {longitude: this.state.curLocation.lng},
            {latitude: this.state.curLocation.lat},
            {pkTenant: this.state.pkTenant});

        let enterpriseUpdateInfo = {
            insertEnterpriseVOs: this.state.insertEnterpriseVOs,
            updateEnterpriseVOs: this.state.updateEnterpriseVOs,
            deleteEnterpriseVOs: this.state.delPkTeamEnt
        };
        let memberUpdateInfo = {
            insertMemberVOs: this.state.insertMemberVOs,
            updateMemberVOs: this.state.updateMemberVOs,
            deleteMemberVOs: this.state.delPkTeamMember
        };
        let param = Object.assign({}, {project}, {enterpriseUpdateInfo}, {memberUpdateInfo});
        // return;
        editWorkFileList(param,
            res => {
                if (res.data.resultCode !== 'busi_ex') {
                    window.location.href = "./workfile.html";
                } else {
                    danger({text: res.data.exMsg});
                }
            },
            error => {
            }
        );
    }
    handlerSetBorderStatus = (data) => {
        for (let name in data) {
            if (data[name] === '') {
                switch(name){
                    case 'sname':
                        this.setState({
                            snameDanger: true
                        });
                        break;
                    case 'scode':
                        this.setState({
                            scodeDanger: true
                        });
                        break;
                    case 'approvalDate':
                        this.setState({
                            approvalDateDanger: true
                        });
                        break;
                }
            } else {
                switch(name){
                    case 'sname':
                        this.setState({
                            snameDanger: false
                        });
                        break;
                    case 'scode':
                        this.setState({
                            scodeDanger: false
                        });
                        break;
                    case 'approvalDate':
                        this.setState({
                            approvalDateDanger: false
                        });
                        break;
                }
            }
        }
    }

    handlerShowManagerModal = () => {
        getManagerList({},
            res => {
                let data = res.data.result;
                data.content.forEach((item, idnex) => {
                    item['key'] = item['userId'];
                })
                this.setState({
                    showModal: true,
                    contentType: 'managerModal',
                    modalSize: 'lg',
                    modalTitle: '项目经理',
                    managerRec: {},
                    managerData: data.content,
                    handlerModalCancel: this.onhide,
                    handlerModalConfirm: this.handlerSaveManager
                });
            },
            error => {
            }
        )
    }
    handlerSaveManager = () => {
        let keysM = Object.keys(this.state.managerRec);
        if (!keysM.length) {
            this.setState({showModal: false});
            return
        }
        let delPkTeamEnt = this.state.delPkTeamEnt;
        let delPkTeamMember = this.state.delPkTeamMember;
        let insertMemberVOs = this.state.insertMemberVOs;
        let enterpriseArray = this.state.enterpriseListData;
        let updateMemberVOs = this.state.updateMemberVOs;
        let insertEnterpriseVOs = this.state.insertEnterpriseVOs;
        let oldEnterpriseKey = sessionStorage.getItem('oldEnterpriseKey');
        let needAddenterpriseArray = true;
        let sameMangerFlag = false;
        
        let managerRecMe = {
            userName: this.state.managerRec.userName,
            userMobile: this.state.managerRec.userMobile,
            userEmail: this.state.managerRec.userEmail,
            pkUser: this.state.managerRec.userId,
            pkEnterprise: this.state.managerRec.defaultEntId,
            userRole:!this.state.isUseNewTeam ? 0 :  this.state.managerRec.defaultRole, 
        };
        this.state.managerRec['teamMemberViewVOs'] = [managerRecMe];
        let newRec = Object.assign({}, this.state.managerRec, {entRole:  !this.state.isUseNewTeam  ? '10' : this.state.managerRec.defaultRole });
        for (let i = 0; i < enterpriseArray.length; i++) {
            const item = enterpriseArray[i];
            for (let itemTeam of item.teamMemberViewVOs){
				if(itemTeam.userId === this.state.managerRec.userId || itemTeam.pkUser === this.state.managerRec.userId ){//重复经理的时候
					item["userId"] = this.state.managerRec.userId;
					item['defaultRole'] = this.state.managerRec.defaultRole;
					item['entRole'] = this.state.managerRec.entRole;
					
					warning({text: `${item.defaultEntName}已存在该项目经理，不可重复选中！`})
					sameMangerFlag = true;
					break;
				}
	
            }
            if(sameMangerFlag){
				break;
			}
            if (item.pkEnterprise == this.state.managerRec.pkEnterprise) {
                needAddenterpriseArray = false;
            }
        }
        if (needAddenterpriseArray && !sameMangerFlag) {
            enterpriseArray.map((item, index) => {
                //删除原有项目经理
                let teamMemberViewVOs = item.teamMemberViewVOs;
                for (let i = 0; i < teamMemberViewVOs.length; i++) {
                    const memberItem = teamMemberViewVOs[i];
                    if (memberItem['userRole'] == 0 || memberItem['userRole'] == "0" || memberItem['pkUser'] === this.state.manager) {
                        memberItem.userRole = this.state.enterpriseRoleArray[i];
                        teamMemberViewVOs.splice(i, 1,memberItem);
                        this.setUpdateMemberVOs(memberItem,updateMemberVOs);
                        break
                    }
                }
                item.teamMemberViewVOs = teamMemberViewVOs;
                return item
            });
            enterpriseArray.push(newRec);
            insertEnterpriseVOs.push(newRec);
            insertMemberVOs.push(managerRecMe);
            this.state.enterpriseRoleArray.push( !this.state.isUseNewTeam  ? '10' : this.state.managerRec.defaultRole.toString());
        } else  if (!sameMangerFlag){
            enterpriseArray.map((item, index) => {
                //删除原有项目经理
                let teamMemberViewVOs = item.teamMemberViewVOs;
                for (let i = 0; i < teamMemberViewVOs.length; i++) {
                    const memberItem = teamMemberViewVOs[i];
                    if (memberItem['userRole'] == 0 || memberItem['pkUser'] === this.state.manager) {
                        memberItem.userRole = this.state.enterpriseRoleArray[index];
                        teamMemberViewVOs.splice(i, 1,memberItem);
                        this.setUpdateMemberVOs(memberItem,updateMemberVOs);
                        break
                    }
                }
                item.teamMemberViewVOs = teamMemberViewVOs;

                //添加最新项目经理
                if (item.pkEnterprise == this.state.managerRec.defaultEntId) {
                    let teamMemberViewVOs = item.teamMemberViewVOs;
                    let num = 0;
                    teamMemberViewVOs.forEach((itemM,index)=>{
                        if(itemM['pkUser'] == this.state.managerRec.userId){
                            itemM.userRole = !this.state.isUseNewTeam ? 0 :  this.state.managerRec.defaultRole, 
                            this.setUpdateMemberVOs(itemM,updateMemberVOs);
                        }else {
                            num += 1
                        }
                    });
                    if(num == teamMemberViewVOs.length){
                       item.teamMemberViewVOs.push(managerRecMe);
                        insertMemberVOs.push(managerRecMe);
                   }
                }
                return item
            });
        }
        if(!sameMangerFlag){
            sessionStorage.setItem('oldEnterpriseKey', this.state.managerRec.pkEnterprise);
		}
        //处理删除团队中的人员 继续切换项目经理为 已经删除的人员
        delPkTeamMember.forEach((itemDel,index)=>{
            if(this.state.managerRec.userId == itemDel.pkUser){
                insertMemberVOs.forEach((item,index)=>{
                    if(this.state.managerRec.userId == item.pkUser){
                        if(itemDel['pkTeamMember']){
                            item['pkTeamMember'] = itemDel['pkTeamMember'];
                            item['changeFlag'] = itemDel['changeFlag'];
                            this.setUpdateMemberVOs(item,updateMemberVOs);
                            insertMemberVOs.splice(index,1);
                        }
                    }
                })
                delPkTeamMember.splice(index,1);
            }
        });
        this.setState({
            showModal: false,
            enterpriseListData: enterpriseArray,
            managerName: this.state.managerRec.userName,
            manager: this.state.managerRec.userId,
            enterpriseRoleArray: this.state.enterpriseRoleArray,
            insertEnterpriseVOs,
            delPkTeamEnt,
            delPkTeamMember,
            insertMemberVOs,
            updateMemberVOs
        });
    };
    setUpdateMemberVOs =(item,updateMemberVOs)=>{
        let num = 0
        for (let i = 0; i < updateMemberVOs.length; i++) {
            const updataItem = updateMemberVOs[i];
            if(updataItem['pkUser'] == item['pkUser']){
                updateMemberVOs.splice(i,1,item)
            }else {
                num += 1
            }
        }
        if(num == updateMemberVOs.length){
            updateMemberVOs.push(item)
        }
    };
    handlerSaveMangerRecord = (item) => {
        this.setState({
            managerRec: Object.assign({}, item, {pkEnterprise: item.defaultEntId})
        });
    }
    handleChange = (value) => {
        let updateEnterpriseVOs = this.state.updateEnterpriseVOs;
        let currentRowValue = this.state.enterpriseListData[this.state.enterpriseDivIndex];
        let count = 0;
        if (this.state.insertEnterpriseVOs.length > 0) {
            this.state.insertEnterpriseVOs.forEach((item, index) => {
                if (currentRowValue.pkEnterprise === item.pkEnterprise) {
                    count++;
                    item['entRole'] = value;
                }
            
            })
        }
        if (this.state.insertMemberVOs.length > 0) {
            this.state.insertMemberVOs.forEach((item, index) => {
                if (currentRowValue.pkEnterprise === item.pkEnterprise) {
                    item.userRole = item.userRole === "0" ? "0" : value;
                }
            })
        }
        if (count === 0) {
            this.state.enterpriseListData[this.state.enterpriseDivIndex]['entRole'] = value;
            this.state.enterpriseListData[this.state.enterpriseDivIndex]['teamMemberViewVOs'].forEach((item) => {
                item['userRole'] = value;
            })
            let countUpdate = 0;
            if (updateEnterpriseVOs.length > 0) {
                updateEnterpriseVOs.forEach((item, index) => {
                    if (currentRowValue.pkEnterprise === item.pkEnterprise) {
                        //item['entRole'] = value;
                        updateEnterpriseVOs.splice(index, 1);
                        countUpdate++;//currentRowValue
                        updateEnterpriseVOs.push(this.state.enterpriseListData[this.state.enterpriseDivIndex]);
                    }
                })
            }
            if (countUpdate === 0) {
                updateEnterpriseVOs.push(this.state.enterpriseListData[this.state.enterpriseDivIndex]);
            }
        }


        this.state.enterpriseRoleArray[this.state.enterpriseDivIndex] = value;

        this.setState({
            defaultValueRole: value,
            enterpriseRoleArray: this.state.enterpriseRoleArray,
            updateEnterpriseVOs
        })
    }
    handlerCreateMembers = (item, index) => () => {
        let membersData = Object.assign({}, item, {role: this.state.enterpriseRoleArray[index]})
        this.setState({
            showModal: true,
            contentType: 'organize',
            modalSize: 'lg',
            modalTitle: '添加成员',
            memberArray:{},
            membersData,
            enterpriseRole: item.entRole,
            handlerModalCancel: this.onhide,
            handlerModalConfirm: this.handlerMemberConfirm
        });
    }
    handlerCancelItem = () => {
        this.setState({
            showModal: true,
            contentType: 'normal',
            modalSize: 'sm',
            modalTitle: '',
            handlerModalCancel: this.onhide,
            handlerModalConfirm: this.handlerCancel
        });
    }
    handlerCancel = () => {
        window.location.href = "./workfile.html";
    }
    handlerDeleteEnterprise = () => {
        let stop = false;
        let delPkTeamEnt = this.state.delPkTeamEnt;
        let insertEnterpriseVOs = this.state.insertEnterpriseVOs;
        let enterpriseData = this.state.enterpriseListData;
        let enterpriseRoleArray = this.state.enterpriseRoleArray;
        let deleteItem = enterpriseData[this.state.chooseDeleteIndex];
        let deleteEnterpriseItem = enterpriseData[this.state.chooseDeleteIndex];
        deleteEnterpriseItem.teamMemberViewVOs.forEach((item, index) => {
            if(item.userRole === '0' || item.userRole === 0 || item.pkUser=== this.state.manager){
                danger({text: '存在项目经理的项目不能删除！'});
                stop = true;
            }
            return;
        })
        if (stop) return;
        insertEnterpriseVOs.forEach((item, index) => {
            if (item['pkEnterprise'] == deleteItem.pkEnterprise) {
                insertEnterpriseVOs.splice(index, 1);
            }
        })
        delPkTeamEnt.push(deleteItem)
        enterpriseData.splice(this.state.chooseDeleteIndex, 1);
        enterpriseRoleArray.splice(this.state.chooseDeleteIndex, 1);

        this.setState({
            enterpriseListData: enterpriseData,
            enterpriseRoleArray,
            showModal: false,
            insertEnterpriseVOs
        });
    }
    handlerShowDeleteModal = (index) => () => {
        this.setState({
            showModal: true,
            modalSize: 'sm',
            modalTitle: '',
            chooseDeleteIndex: index,
            contentType: 'enterpriseDelete',
            handlerModalCancel: this.onhide,
            handlerModalConfirm: this.handlerDeleteEnterprise
        });
    }
    handlerChooseDivIndex = (index) => () => {
        this.setState({
            enterpriseDivIndex: index
        });
    }
    handleDropSearch = (value) => {
        let projectState = this.getProjectState(value);
        this.setState({
            projectState,
            projectStateValue: value
        })
    }
    getProjectState = (state) => {
        let projectState = '';
        if (state == '-1') {
            projectState = '创建';
        } else if (state == '0') {
            projectState = '施工中';
        } else if (state == '1') {
            projectState = '竣工';
        } else if (state == '-2') {
            projectState = '暂停';
        }
        return projectState
    }
    handleProcedureChange = (a) => {
		this.setState({
			procedureValue: a
		})
	}
	filterProcedures = (val, option) => {
		if(option.props.children.indexOf(val)!=-1){
			return true;
		}
		return false;
    }
    mapModalClose = (lng, lat, address) => {
		document.getElementById('app').style.overflow = "auto";

		this.setState({
			mapModalShow: false
		});
		if (lng) {
			this.setState({
				curLocation:{
					lng,
					lat,
					address,
				}
			})
		}
	}
	openMapModal= ()=>{
		document.getElementById('app').style.overflow = "hidden";
		this.setState({
			mapModalShow: true,
		})
    }
    
    clearPosition=()=>{
		this.setState({
			curLocation:{
			}
		})
	}

    render() {
        let {
            code, 
            name, 
            description, 
            checked, 
            showModal, 
            contentType, 
            modalSize, 
            modalTitle, 
            enterpriseListData, 
            managerName, 
            userName, 
            snameDanger, 
            scodeDanger, 
            approvalDateDanger, 
            enterpriseRoleArray, 
            creationtime, 
            ncStatus, 
            procedureList,
            procedureValue,
        } = this.state;
        return (
            <App>
                <CommonModal show={showModal}
                             cancel={this.state.handlerModalCancel}
                             confirm={this.state.handlerModalConfirm}
                             hide={this.onhide}
                             backdrop={true}
                             content={this.getCompnents(contentType)}
                             size={modalSize}
                             title={modalTitle}
                >
                </CommonModal>
                <div className="header clearfix">
                    <div className="bread-crumb">
                        <Breadcrumb>
                            <Breadcrumb.Item href="./workfile.html">
                                项目列表
                            </Breadcrumb.Item>
                            <Breadcrumb.Item href="./workeditfileitem.html">
                                编辑项目
                            </Breadcrumb.Item>
                        </Breadcrumb>
                    </div>
                    <div className="item-user">
                        <p>创建人：{userName}</p>
                        <p>创建时间：{fmtDate(creationtime)}</p>
                    </div>
                </div>
                <div className="basedata--content">
                    <div className="base--header clearfix">
                        <p>基本信息</p>
                        <div className="btn-group">
                            <Button colors="primary" onClick={this.handlerSaveItem}>保存</Button>
                            <Button onClick={this.handlerCancelItem}>取消</Button>
                        </div>
                    </div>
                    <div className="base--content">
                        <Row>
                            <Col md={6} xs={6} sm={6}>
                                <div className='base--input__group clearfix'>
                                    <i className="red--icon">*</i>
                                    <span className="name">项目编码：</span>
                                    <FormControl size="lg" disabled={ncStatus} placeholder="20个数字、英文以内"
                                                 onChange={this.handlerSaveCode} value={code}
                                                 className={scodeDanger ? 'danger-boder' : ''}/>
                                    {scodeDanger ? <b className="notice--tip">内容不能为空</b> : ''}
                                </div>
                            </Col>
                            <Col md={6} xs={6} sm={6}>
                                <div className='base--input__group clearfix'>
                                    <i className="red--icon">*</i>
                                    <span className="name">项目名称：</span>
                                    <FormControl size="lg" disabled={ncStatus} placeholder="50个汉字、英文、数字、符号以内"
                                                 onChange={this.handlerSaveName} value={name}
                                                 className={snameDanger ? 'danger-boder' : ''}/>
                                    {snameDanger ? <b className="notice--tip">内容不能为空</b> : ''}
                                </div>
                            </Col>
                            <Col md={6} xs={6} sm={6}>
                                <div className='base--input__group clearfix'>
                                    <span className="name">项目经理：</span>
                                    <FormControl size="lg" disabled={ncStatus} placeholder={'请点击选择！'}
                                                 onClick={this.handlerShowManagerModal} value={managerName}/>
                                </div>
                            </Col>
                            <Col md={6} xs={6} sm={6}>
                                <div className='base--input__group clearfix'>
                                    <i className="red--icon">*</i>
                                    <span className="name">项目状态：</span>
                                    {this.state.projectStatusName ?
                                        <FormControl size="lg" disabled={true} value={this.state.projectStatusName}/> :
                                        <Select className='base--input__dropInput '
                                                value={this.state.projectState}
                                                disabled={ncStatus}
                                                onSelect={this.handleDropSearch}
                                        >
                                            <Select.Option value="-1">创建 </Select.Option>
                                            <Select.Option value="0">施工中</Select.Option>
                                            <Select.Option value="1">竣工</Select.Option>
                                            <Select.Option value="-2">暂停 </Select.Option>
                                        </Select>}
                                </div>
                            </Col>

                            <Col md={6} xs={6} sm={6}>
                                <div className='base--input__group clearfix'>
                                    <i className="red--icon">*</i>
                                    <span className="name">立项日期：</span>
                                    <DatePicker
                                        format={"YYYY-MM-DD"}
                                        onSelect={this.onStartSelect}
                                        onChange={this.onChange}
                                        locale={zhCN}
                                        placeholder={'选择日期时间'}
                                        disabled={ncStatus}
                                        value={moment(this.state.startDate)}
                                        className={approvalDateDanger ? 'danger-boder' : ''}
                                    />
                                    {approvalDateDanger ? <b className="notice--tip">内容不能为空</b> : ''}
                                </div>
                            </Col>

                            <Col md={6} xs={6} sm={6}>
                                <div className='base--input__group clearfix'>
                                    <span className="name">重点项目：</span>
                                    <div className='switch--containers'>
                                        <Switch checked={checked} disabled={ncStatus}
                                                onChange={this.handlerSwitchChoose}/>
                                    </div>

                                    {
                                        this.state.endDate ?
                                            <div className='base--input__closeTime'>
                                                <span>验收日期:</span>
                                                <span style={{marginLeft: '6px'}}>{fmtDate(this.state.endDate)}</span>
                                            </div> :
                                            null
                                    }
                                </div>
                            </Col>
                            <Col md={6} xs={6} sm={6}>
                            <div className='base--input__group clearfix'>
									<span className="name">项目组织：</span>
									<FormControl size="lg" disabled={true} placeholder=""  value={this.state.orgName} className={ scodeDanger ? 'danger-boder': ''}/>

								</div>
							</Col>
                        </Row>
                        <Row>
                            <Col md={6} xs={6} sm={6}>
                                <div className='base--input__group clearfix base--input__groupMutiSelect'>
                                    <span className="name">适用工序：</span>
                                    <Select
                                        multiple
                                        className={'base--input__MultiSelect'}
                                        onChange={this.handleProcedureChange}
                                        placeholder="请点击选择工序"
                                        value={procedureValue || []}
                                        dropdownMatchSelectWidth
                                        showSearch
                                        notFoundContent="没有相关条目"
                                        filterOption={this.filterProcedures}
                                    // size = "lg"
                                    >
                                        {
                                            procedureList.map(cur => {
                                                return <Select.Option key={cur.pkProcedure}>{cur.scode + ' ' + cur.sname}</Select.Option>
                                            })
                                        }
                                    </Select>
                                </div>
                            </Col>
                            <Col md={6} xs={6} sm={6}>
                                <div className='base--input__group clearfix'>
                                    <span className="name">项目地址：</span>
                                    <a href="javascript:;" className='refer-map' onClick={this.openMapModal}>关联地图</a>
                                    <FormControl className='map-text' size="lg" disabled value={this.state.curLocation.address || ''} />
									<i className="clear-position-icon" onClick = {this.clearPosition}></i>
                                </div>
                            </Col>
                            <Col md={12} xs={12} sm={12}>
                                <div className='base--input__group clearfix'>
                                    <span className="name">项目描述：</span>
                                    <textarea size="lg" placeholder={'请输入'} disabled={ncStatus}
                                              value={this.state.description} onChange={this.handlerSaveDescription}/>
                                </div>
                            </Col>
                        </Row>
                    </div>
                </div>
                <div className="enterprise--basedata">
                    <div className="enterprise--header clearfix">
                        <p>企业和团队</p>
                        <a href="javascript:;" onClick={this.handlerCreateEnterprise}>
                            添加企业
                            <i className="enterprise--icon"></i>
                        </a>
                    </div>
                    {enterpriseListData.length !== 0 &&
                    enterpriseListData.map((item, index) => {
                        return <div className="enterprise--content" onClick={this.handlerChooseDivIndex(index)}>
                            <div className="enterprise--item">
                                <div className="item--header">
                                    <Row>
                                        <Col md={2} xs={2} sm={2}>
                                            {this.state.isUseNewTeam ? 
                                                <Select
                                                    size="lg"
                                                    style={{width: 150, marginLeft: 24, marginTop: 8}}
                                                    onChange={this.handleChange}
                                                    placeholder={'请选择'}
                                                    value={enterpriseRoleArray[index]}
                                                    disabled = {this.state.isUseNewTeam}//现规则， 一个租户下的一个企业只可以有一个角色，不允许修改了
                                                >
                                                    <Option value="10">业主方</Option>
                                                    <Option value="20">施工方</Option>
                                                    <Option value="30">监理方</Option>
                                                    <Option value="40">设计方</Option>
                                                    <Option value="50">客户方</Option>
                                                 
                                                </Select>
                                                :
                                                <Select
                                                    size="lg"
                                                    style={{width: 150, marginLeft: 24, marginTop: 8}}
                                                    onChange={this.handleChange}
                                                    placeholder={'请选择'}
                                                    value={enterpriseRoleArray[index]}
                                                >
                                                    <Option value="10">业主方</Option>
                                                    <Option value="20">施工方</Option>
                                                    <Option value="30">监理方</Option>
                                                </Select>
                                            }
                                           
                                        </Col>
                                        <Col md={10} xs={10} sm={10} className="clearfix">
                                            <p>{item.defaultEntName || item.name}</p>
                                            <a href="javascript:;" onClick={this.handlerShowDeleteModal(index)}>删除</a>
                                        </Col>
                                    </Row>
                                </div>
                                <div className="item--content">
                                    <Row>
                                        <Col md={2} xs={2} sm={2}>
                                            <p>团队成员</p>
                                        </Col>
                                        <Col md={10} xs={10} sm={10}>
                                            <a href="javascript:;" className="btn--add__member"
                                               onClick={this.handlerCreateMembers(item, index)}>
                                                添加成员
                                                <i className="member--icon"></i>
                                            </a>
                                            <Table data={item.teamMemberViewVOs} columns={this.getColumns()}></Table>
                                        </Col>
                                    </Row>
                                </div>
                            </div>
                        </div>
                    })
                    }
                </div>
                <MapModal
					show={this.state.mapModalShow}
					onClose={this.mapModalClose}
					initLocation={this.state.curLocation}
				/>
            </App>
        )
    }
}